﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LPV_POS.Module;
using DevExpress.XtraGrid.Views.Base;

namespace LPV_POS.mh_pos.mh_cauhinh
{
    public partial class mh_dangnhap_MENU : DevExpress.XtraEditors.XtraForm
    {
        public mh_dangnhap_MENU()
        {
            InitializeComponent();
        }
        Boolean iloadform = false;
        DataTable tbMenu=null;
        string username = "";
        private void mh_dangnhap_Load(object sender, EventArgs e)
        {
            this.ShowCombo();
            this.ShowData();
            iloadform = true;
            this.SetStatus_btn(chon.None);


        }
        void ShowCombo()
        {
            thuvien othuvien = new thuvien();
            string sSQL = "";

            sSQL =  "SELECT OBJID = NULL, OBJNAME = '' " +
                    " UNION " +
                    "SELECT OBJID, OBJNAME FROM DM_NHANVIEN "+
                    "ORDER BY OBJNAME ";
            DataTable tbDM_NHANVIEN = othuvien.SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new string[] { sSQL });
            cboNhanVien.Datasource = tbDM_NHANVIEN;
            //cboNhanVien.DisplayField
            cboNhanVien._Init();
        }
        void ShowData()
        {
            thuvien othuvien = new thuvien();

            DataTable tbDM_DANGNHAP;
            string sSQL = "";

            sSQL = "SELECT CHON = CAST(0 AS BIT), m.menu_ma, m.ten_form, m.ten_control, m.tag_control, m.menu_tieude " +
                   "FROM MENU m " +
                   "ORDER BY m.menu_ma";
            tbMenu = othuvien.SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new string[] { sSQL });
            grdPhanQuyen.DataSource = tbMenu;

            sSQL = "SELECT dd.*, DM_NHANVIEN_TEN = dn.OBJNAME, dn.CHUCVU " +
                   "FROM DM_DANGNHAP dd " +
                   "	LEFT JOIN DM_NHANVIEN dn ON dd.MA_NHANVIEN = dn.OBJID";
            tbDM_DANGNHAP = othuvien.SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new string[] { sSQL });
            grdDanhSach_DangNhap.DataSource = tbDM_DANGNHAP;

            
        }

        private void gvDanhSach_DangNhap_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                this.SetStatus_btn(chon.None);
                DataRowView drv = (DataRowView)gvDanhSach_DangNhap.GetFocusedRow();
                username = drv["USERNAME"] + "";

                string sSQL = "SELECT dd.*, DM_NHANVIEN_TEN = dn.OBJNAME, dn.CHUCVU " +
                               "FROM DM_DANGNHAP dd " +
                               "	LEFT JOIN DM_NHANVIEN dn ON dd.MA_NHANVIEN = dn.OBJID " +
                               "WHERE dd.USERNAME = '" + username + "'";
                DataTable tbDM_DANGNHAP = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", 
                                                                    new string[] { "@sSQL" }, 
                                                                    new string[] { sSQL });

                this.showinfo(tbDM_DANGNHAP.Rows[0]);
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }

        #region"    showinfo"
        void showinfo(DataRow _drUser)
        {
            this.showinfoMenu(_drUser);
            this.showinfoUser(_drUser);
        }
        
        //  hien thi phan quyen
        void showinfoMenu(DataRow _drUser)
        {
            if (_drUser == null) return;
            

            foreach (DataRow dr in tbMenu.Rows)
                dr["chon"] = 0;

            try
            {
                Int64 iquyen = Int64.Parse("0" + _drUser["IQUYEN"]);


                int iMAX = int.Parse("0" + tbMenu.Compute("MAX(menu_ma)", ""));

                for (int imaxMenu_id = iMAX; imaxMenu_id >= 0; imaxMenu_id--)
                {
                    double iTMP = Math.Pow(2, imaxMenu_id);

                    if (Math.Pow(2, imaxMenu_id) <= iquyen &&
                        Math.Pow(2, imaxMenu_id) > iquyen / 2)
                    {
                        if (tbMenu.Select("menu_ma=" + imaxMenu_id).Length == 1)
                            tbMenu.Select("menu_ma=" + imaxMenu_id)[0]["CHON"] = 1;

                        iquyen = iquyen - (Int64)Math.Pow(2, imaxMenu_id);
                    }
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }

        void showinfoUser(DataRow _drUser)
        {
            txtDangNhap.Text = _drUser["USERNAME"] + "";
            DateTime tTU_GIO = DateTime.Now;
            DateTime tDEN_GIO = DateTime.Now;
            if (_drUser["TU_GIO"] + "" != "")
                DateTime.TryParse(_drUser["TU_GIO"] + "", out tTU_GIO);
            if (_drUser["DEN_GIO"] + "" != "")
                DateTime.TryParse(_drUser["DEN_GIO"] + "", out tDEN_GIO);

            txtTuGio.Time = tTU_GIO; 
            txtDenGio.Time = tDEN_GIO; 
            cboCaLamViec.Text = _drUser["OBJNAME"] + "";
            if (_drUser["MA_NHANVIEN"] + "" != "")
                cboNhanVien._SetselectedID(_drUser["MA_NHANVIEN"] + "");
            else
                cboNhanVien.SelectedIndex = 0;
        }
        #endregion

        private void btnLuuQuyen_Click(object sender, EventArgs e)
        {
            if (username == "")
                return;

            
            Int64 iq = 0;
            if (tbMenu.Select("chon=1").Length == 0)
            {
                MessageBox_LPV.Show("Phải chọn ít nhất 1 quyền.");
                return;
            }

            foreach (DataRow dr in tbMenu.Select("chon=1"))
                iq += (Int64)Math.Pow(2, int.Parse("" + dr["menu_ma"]));

            thuvien othuvien = new thuvien();

            string sSQL = "UPDATE DM_DANGNHAP SET IQUYEN = " + iq + " WHERE USERNAME = '" + username + "'";


            othuvien.SP_Update("SP_EXECUTESQL",
                                new string[] { "@sSQL" },
                                new object[] { sSQL });

            //DataRow drUser_hienhanh = gvDanhSach_DangNhap.GetDataRow(gvDanhSach_DangNhap.FocusedRowHandle);
            //drUser_hienhanh["IQUYEN"] = iq;

            MessageBox_LPV.Show("Lưu thành công");
            grdPhanQuyen.Refresh();
        }

        // xoa mot phan quyen
        private int f_delete_phanquyen(int maphanquyen)
        {
            int ketqua = 0;
            ketqua = new thuvien().SP_Update("sp_DM_DANGNHAP",
                                                                   new string[] { "@flag", "@OBJID" },
                                                                   new object[] { 3, maphanquyen });
            return ketqua;

        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void chkCheck_All_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow dr in tbMenu.Rows)
                dr["CHON"] = chkCheck_All.Checked;
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            this.SetStatus_btn(chon.Sua);
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            txtTuGio.Time = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, 0, 0);
            txtDenGio.Time = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, 59, 59);
            txtDangNhap.Text = "";
            cboCaLamViec.Text = "";
            cboNhanVien.SelectedIndex = 0;
            this.SetStatus_btn(chon.Them);
        }

        private void btnLuu_NVDangNhap_Click(object sender, EventArgs e)
        {
            if (this.Save())
            {                
                MessageBox_LPV.Show("Lưu thành công");
                this.SetStatus_btn(chon.None);
                this.ShowData();
            }
        }
        Boolean Save()
        {
            if (cboNhanVien.Text== "")
            {
                MessageBox_LPV.Show("Nhập thông tin nhân viên");
                return false;
            }
            if (txtDangNhap.Text == "")
            {
                MessageBox_LPV.Show("Nhập thông tin đang nhập");
                return false;
            }
            if (cboCaLamViec.Text == "")
            {
                MessageBox_LPV.Show("Chọn ca làm việc");
                return false;
            }
            //int chiso;
            if (btnThem.Enabled)//SUA--SUA--SUA--SUA--SUA--SUA--SUA--SUA--SUA--SUA--SUA--SUA--SUA--SUA--SUA--SUA--
            {
                DataRow dr = gvDanhSach_DangNhap.GetDataRow(gvDanhSach_DangNhap.FocusedRowHandle);

                DataTable tb = (DataTable)grdDanhSach_DangNhap.DataSource;
                if (tb.Select("USERNAME = '" + txtDangNhap.Text + "' AND OBJID <> " + dr ["OBJID"]+ "").Length > 0)
                {
                    MessageBox.Show("Mã đăng nhập này đã tồn tại");
                    return false;
                }
                //   chiso = gvDanhSach_DangNhap.FocusedRowHandle;
                

                int irt = new thuvien().SP_Update("sp_DM_DANGNHAP",
                                            new string[] { "@flag", "@OBJCODE", "@OBJNAME", "@USERNAME", 
                                                        "@MA_NHANVIEN", "@TU_GIO", "@DEN_GIO", "@OBJID"},
                                            new object[] { 2, cboCaLamViec.Text, cboCaLamViec.Text,txtDangNhap.Text,
                                                        cboNhanVien._GetselectedID(), txtTuGio.Time, txtDenGio.Time, dr["OBJID"]});
                if (irt == -1)
                    return false;
                // gvDanhSach_DangNhap.FocusedRowHandle = chiso;
            }
            else if (btnSua.Enabled)//THEM--THEM--THEM--THEM--THEM--THEM--THEM--THEM--THEM--THEM--THEM--THEM--
            {
                DataTable tb = (DataTable)grdDanhSach_DangNhap.DataSource;
                if (tb.Select("USERNAME = '" + txtDangNhap.Text + "'").Length > 0)
                {
                    MessageBox.Show("Mã đăng nhập này đã tồn tại");
                    return false;
                }
                new thuvien().SP_Update("sp_DM_DANGNHAP",
                                        new string[] { "@flag", "@OBJCODE", "@OBJNAME", "@USERNAME", 
                                                        "@MA_NHANVIEN", "@TU_GIO", "@DEN_GIO"},
                                        new object[] { 1, cboCaLamViec.Text, cboCaLamViec.Text,txtDangNhap.Text,
                                                        cboNhanVien._GetselectedID(), txtTuGio.Time, txtDenGio.Time});
                //gvDanhSach_DangNhap.FocusedRowHandle = gvDanhSach_DangNhap.RowCount;
            }
                
            return true;
        }
        enum chon
        {
            None,
            Them,
            Sua
        }
        void SetStatus_btn(chon _ochon)
        {
            if (_ochon == chon.None)
            {
                btnLuu_NVDangNhap.Enabled = false;
                btnThem.Enabled = true;
                btnSua.Enabled = true;
            }
            else if (_ochon == chon.Them)
            {
                btnLuu_NVDangNhap.Enabled = true;
                btnThem.Enabled = false;
                btnSua.Enabled = true;
            }
            else if (_ochon == chon.Sua)
            {
                btnLuu_NVDangNhap.Enabled = true;
                btnThem.Enabled = true;
                btnSua.Enabled = false;
            }
        }

        private void btnCaLamViec_Click(object sender, EventArgs e)
        {
            mh_chu omh_chu = new mh_chu();
            string sSo= omh_chu.ShowForm("Ca làm việc", cboCaLamViec.Text, 100, 100, false);
            if (omh_chu.DialogResult == DialogResult.OK)
                cboCaLamViec.Text = sSo;
            
        }

        private void gvDanhSach_DangNhap_Click(object sender, EventArgs e)
        {
            DataTable tb = (DataTable)grdDanhSach_DangNhap.DataSource;

            if (tb.Rows.Count == 1)
                this.gvDanhSach_DangNhap_FocusedRowChanged(null, null);
        }

        private void btnDangNhap_Click(object sender, EventArgs e)
        {
            mh_so omh_so = new mh_so("Đăng nhập", int.Parse("0" + txtDangNhap.Text)); 
            int iso = omh_so.ShowForm();
            if (omh_so.DialogResult == DialogResult.OK)
                txtDangNhap.Text = omh_so.txt_ketqua.Text;
        }

        private void bton_xoa_Click(object sender, EventArgs e)
        {
            Mod_messagebox mess = new Mod_messagebox();
            int ketqua = 0;
            if (grdDanhSach_DangNhap.MainView.RowCount > 0)
            {
                int maphanquyen = int.Parse(gvDanhSach_DangNhap.GetRowCellValue(gvDanhSach_DangNhap.FocusedRowHandle, col_ma) + "");
                ketqua = f_delete_phanquyen(maphanquyen);
                if (ketqua != -1)
                {
                    // xoa mot dong trong luoi don vi tinh
                    int chiso;
                    chiso = ((ColumnView)grdDanhSach_DangNhap.Views[0]).FocusedRowHandle;
                    DataView tam = (DataView)grdDanhSach_DangNhap.Views[0].DataSource;
                    tam.Delete(chiso);
                    mess.messagebox_pos("Thông báo", "Xóa thành công", loaithongbao.thongtin.GetHashCode());
                }
                else
                {
                    mess.messagebox_pos("Thông báo", "Xóa không thành công", loaithongbao.canhbao.GetHashCode());
                }
            }
       
            
        }

        private void txtDangNhap_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }
    }
}